package com.android.thought.badboys.PhoneBook;

import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.RawContacts;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.thought.badboys.BadBoysApplication;
import com.android.thought.badboys.Model;
import com.android.thought.badboys.R;
import com.android.thought.badboys.Action.IPhoneAccessAction;
import com.android.thought.badboys.Action.IPhoneBookAction;
import com.android.thought.badboys.Info.PhoneInfo;
import com.android.thought.badboys.Info.SelectionPhoneInfo;

public class PhoneBookActvity extends Activity implements OnClickListener, IPhoneBookAction {

	public class PhoneAdapter extends BaseAdapter implements OnClickListener {
		private Context mContext;
		ArrayList<PhoneInfo> mList = null;

		public PhoneAdapter(Context context, List<PhoneInfo> list) {
			mContext = context;
			mList = (ArrayList<PhoneInfo>) list;
		}

		public int getCount() {
			return mList.size();
		}

		public PhoneInfo getItem(int position) {
			return mList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		@Override
		public void notifyDataSetChanged() {

			super.notifyDataSetChanged();
		}

		public void notifyDataSetChanged(ArrayList<PhoneInfo> list) {

			mList = list;
			super.notifyDataSetChanged();
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			Warrper warrper ;
			if (convertView == null) {
				view = LayoutInflater.from(mContext).inflate(R.layout.phone_row, null);
			} else {
				view = (View) convertView;
			}
			
			Object obj = view.getTag();
			
			if ( obj == null || ! (obj instanceof Warrper) ) {
				warrper = new Warrper(view);
				view.setTag(warrper);
			} else { 
				warrper = (Warrper) obj;
			}

			final TextView textview_number = warrper .getTextview_Number();
			final TextView textview_name = warrper .getTextview_Name();
			final View pView = warrper .getPView();

			final PhoneInfo info = getItem(position);

			textview_name.setText(info.getName());
			textview_number.setText(info.getPhoneNumber());
			pView.setTag(R.id.ids_item_tag, info);
			pView.setOnClickListener(this);

			return view;
		}

		@Override
		public void onClick(View v) {

			Object obj = v.getTag(R.id.ids_item_tag);
			
			if ( obj != null && obj instanceof PhoneInfo ) {
				if ( mActionDailog == null ) 
					mActionDailog = new ActionDialog(PhoneBookActvity.this, PhoneBookActvity.this);
				
				
				mActionDailog.setData((PhoneInfo)obj, mIsSection);
				mActionDailog.show();
			}
		}
		
		
	}

	class Warrper {
		View mPview = null;
		TextView mTextview_name= null;
		TextView mTextview_number = null;
		
		public Warrper(View view) {
			this.mPview = view.findViewById(R.id.linear_phone_row_p);
			this.mTextview_number = (TextView) view.findViewById(R.id.textview_phone_number);
			this.mTextview_name= (TextView) view.findViewById(R.id.textview_phone_name);
		}
		
		public View getPView(){
			return this.mPview;
		}
		
		public TextView getTextview_Name() { 
			return this.mTextview_name;
		}
		public TextView getTextview_Number() { 
			return this.mTextview_number;
		}
	}
	
	class PhoneTask extends AsyncTask<IPhoneBookAction, Void, List<PhoneInfo>> {
		IPhoneBookAction mListener;

		ProgressDialog mProgressDialog;
		Context mContext;

		public PhoneTask(Context context) {
			mContext = context;

		}

		@Override
		protected List<PhoneInfo> doInBackground(IPhoneBookAction... params) {

			if (params != null && params.length > 0) {
				mListener = params[0];
				return onLoadPhoneBook();
			}

			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			this.mProgressDialog = new ProgressDialog(mContext);
			this.mProgressDialog.setMessage("잠시만 기다려 주세요. \n전화번호부를 로딩 중 입니다.");
			this.mProgressDialog.setCancelable(true);
			this.mProgressDialog.show();

			this.mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					onCancelled();
				}
			});

		}

		@Override
		protected void onCancelled() {

			super.onCancelled();
		}

		@Override
		protected void onPostExecute(List<PhoneInfo> result) {
			super.onPostExecute(result);

			if (this.mProgressDialog != null)
				this.mProgressDialog.dismiss();

			this.mProgressDialog = null;
			this.mContext = null;

			if (this.mListener != null)
				this.mListener.onComplate(result);
		}

		public List<PhoneInfo> onLoadPhoneBook() {
			SparseArray<PhoneInfo> list  = new SparseArray<PhoneInfo>();
			
			final Cursor phoneNumberCursor = getContentResolver().query(Phone.CONTENT_URI,
					new String[] { Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER , Phone.CONTACT_ID }, null, null,
					Phone.DISPLAY_NAME );

			if (phoneNumberCursor != null && phoneNumberCursor.getCount() > 0) {

				phoneNumberCursor.moveToFirst();

				int index_Id = phoneNumberCursor.getColumnIndex(Phone._ID);
				int index_Contact_Id = phoneNumberCursor.getColumnIndex(Phone.CONTACT_ID);
				int index_name = phoneNumberCursor.getColumnIndex(Phone.DISPLAY_NAME);
				int index_number = phoneNumberCursor.getColumnIndex(Phone.NUMBER);
				while (!phoneNumberCursor.isAfterLast()) {
					/*
					 * String[] columnNames = phoneNumberCursor.getColumnNames(); Log.i("CH_DEBUG",
					 * "############################ START #########################");
					 * 
					 * for (int i = 0; i < columnNames.length; i++) { int indexs =
					 * phoneNumberCursor.getColumnIndex(columnNames[i]);
					 * 
					 * Log.e("CH_DEBUG", "##### V : " + columnNames[i] + " #### VALUE : " +
					 * phoneNumberCursor.getString(indexs));
					 * 
					 * } Log.d("CH_DEBUG", "############################ END #########################");
					 */

					
					int contactId = phoneNumberCursor.getInt(index_Contact_Id);
					
					PhoneInfo  info = null;
					
					if ( (info =  list.get(contactId)) == null  ) {
						info = new PhoneInfo();
						info.setId(phoneNumberCursor.getInt(index_Id));
						info.setContact_id(contactId);
						info.setName(phoneNumberCursor.getString(index_name));
						info.setPhoneNumber(phoneNumberCursor.getString(index_number));
						
						list.put(contactId, info);
						
					} else  {
						info.addSubNumber(phoneNumberCursor.getString(index_number));
						list.append(contactId, info);
					}
					phoneNumberCursor.moveToNext();
				}
			}

			if (phoneNumberCursor != null)
				phoneNumberCursor.close();
			/*		
			Cursor cu = getContentResolver().query(RawContacts.CONTENT_URI, null, null, null, null);
			
			
			cu.moveToFirst();
		
			while (cu.moveToNext()) {
				type type = (type) cu.nextElement();
				
			}
			  String[] columnNames = phoneNumberCursor.getColumnNames(); Log.i("CH_DEBUG", "############################ START #########################");
			  
			  for (int i = 0; i < columnNames.length; i++) { int indexs =
			  phoneNumberCursor.getColumnIndex(columnNames[i]);
			  
			  Log.e("CH_DEBUG", "##### V : " + columnNames[i] + " #### VALUE : " +
			  phoneNumberCursor.getString(indexs));
			  
			 } Log.d("CH_DEBUG", "############################ END #########################");
			 
			*/
			
			ArrayList<PhoneInfo> resultList = new ArrayList<PhoneInfo>();
			
			
			list.size();
			for( int k =0 ;  k < list.size(); k++ ) {
				resultList.add(list.get(list.keyAt(k)));
			}
			
			Collections.sort(resultList, new PhoneInfo());
			
			return resultList;
		}

	}

	ListView mListview = null;

	PhoneAdapter mPhoneBookAdaper;
	
	ActionDialog mActionDailog = null;
			
	Model mModel = null;
	
	SelectionPhoneInfo mAdministorPhoneGroupInfo;
	
	IPhoneAccessAction mPhoneAccessAction = new IPhoneAccessAction() {
		
		@Override
		public void onSaveComplated(boolean isSucess) {
		}
		
		@Override
		public void onLoadComplated(SelectionPhoneInfo info) {
			mAdministorPhoneGroupInfo = info;
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Application app = getApplication();
		
		if ( ! (app instanceof BadBoysApplication) )
			finish();
		
		mModel = ((BadBoysApplication)app).getModel();
		
		mModel.getAdministrationPhoneInfo(this, mPhoneAccessAction);
		
		setContentView(R.layout.phonebook_layer);

		this.findViewById(R.id.btn_phone_all).setOnClickListener(this);
		this.findViewById(R.id.btn_phone_check).setOnClickListener(this);

		mListview = (ListView) this.findViewById(R.id.listview_phonebook);

		new PhoneTask(this).execute(this);
	}

	boolean mIsSection = false;
	@Override
	public void onClick(View arg0) {
		final int id = arg0.getId();
		
		if ( id == R.id.btn_phone_all )  { 
			mIsSection = false;
			new PhoneTask(this).execute(this);
		} else if (id ==  R.id.btn_phone_check ) {
			mIsSection = true;
			onComplate(mAdministorPhoneGroupInfo.getList());
			
		}
	}

	@Override
	public void onComplate(List<PhoneInfo> list) {
		if (mPhoneBookAdaper == null) {
			mPhoneBookAdaper = new PhoneAdapter(this, list);
			mListview.setAdapter(mPhoneBookAdaper);
		} else
			mPhoneBookAdaper.notifyDataSetChanged((ArrayList<PhoneInfo>) list);
	}

	@Override
	public void onPhoneBookRemove(PhoneInfo info) {
		
		mAdministorPhoneGroupInfo.removePhoneInfo(info);
		String where = "contact_id = " + info.getContact_id() ;
		
		getContentResolver().delete(RawContacts.CONTENT_URI
															.buildUpon()
															.appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true")
															.build()
				, where, null);
		
		// 선택보기에서 전화번호 삭제 이면.
		if ( mIsSection ) {
			this.onComplate(mAdministorPhoneGroupInfo.getList());
		} else {
			new PhoneTask(this).execute(this);
		}
	}

	@Override
	public void onRegister(PhoneInfo info) {
		if ( !mIsSection) { 
			mAdministorPhoneGroupInfo.addPhoneInfo(info);
		}
	}

	@Override
	public void onRemove(PhoneInfo info) { 
		mAdministorPhoneGroupInfo.removePhoneInfo(info);
		
		// 선택 보기에서   선택 제외시 갱신
		if ( mIsSection ) {
			this.onComplate(mAdministorPhoneGroupInfo.getList());
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
}
